package com.beiing.tianshuai.tianshuai.interest;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.RelativeLayout;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.activity.InterestVideoPublishSuccessActivity;
import com.beiing.tianshuai.tianshuai.base.BaseFragment;
import com.beiing.tianshuai.tianshuai.entity.CodeBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.huodong.adapter.MyPagerAdapter;
import com.beiing.tianshuai.tianshuai.interest.entity.InterestBean;
import com.beiing.tianshuai.tianshuai.interest.presenter.InterestPresenter;
import com.beiing.tianshuai.tianshuai.interest.view.InterestViewImpl;
import com.beiing.tianshuai.tianshuai.mine.ui.LoginActivity;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.bingoogolapple.bgabanner.BGAOnNoDoubleClickListener;

/**
 * Create by Jinni on 2017-11-19
 * <p>
 * 描述：兴趣界面，主要展示用户感兴趣的主题相关小视频。
 */
public class InterestFragment extends BaseFragment implements InterestViewImpl {

    /**
     * ToolBar
     */
    @BindView(R.id.toolbar)
    Toolbar mToolbar;

    /**
     * 网络请求失败提示
     * 点击重新获取网络连接
     */
    @BindView(R.id.rv_request_fail)
    RelativeLayout mRlRequestFailed;

    /**
     * 顶部导航栏
     */
    @BindView(R.id.tl_interest)
    SlidingTabLayout mTlInterest;

    /**
     * 导航栏
     */
    @BindView(R.id.toolbar_container)
    FrameLayout mToolbarContainer;

    /**
     * 内容view pager
     */
    @BindView(R.id.vp_content)
    ViewPager mVpContent;

    /**
     * 发布视频按钮
     */
    @BindView(R.id.ib_publish_video)
    ImageButton mBtnPublishVideo;

    /**
     * 发布视频请求码
     */
    public static final int REQUEST_CODE_PUBLISH_VIDEO = 0;

    /**
     * 是否第一次加载，第一次加载时初始化顶部tabLayout
     */
    private boolean isFirstLoad = true;

    /**
     * 防止网络请求超时，在请求失败时重新请求接口，以此记录重新请求的次数，当超过5次时不再重新请求数据。
     */
    private int retryCount = 0;

//    /**
//     * toolbar 是否显示
//     */
//    public static boolean isToolbarShow = true;

    /**
     * fragments集合
     */
    private ArrayList<Fragment> mFragments = new ArrayList<>();

    /**
     * presenter
     */
    private InterestPresenter mPresenter = new InterestPresenter(this);

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_interest;
    }

    @Override
    protected void init(View mView) {
        mContext = getActivity();
//        initStatusBar();
        mPresenter.getInterestInfo("", "1", "", UserInfoBean.getUid(mContext), 1);
        initListener();
    }

    /**
     * 初始化状态栏
     */
    private void initStatusBar() {
        QMUIStatusBarHelper.setStatusBarLightMode(getActivity());
        int statusBarHeight = QMUIStatusBarHelper.getStatusbarHeight(mContext);
        mToolbar.setPadding(0, statusBarHeight, 0, 0);
    }

    private void initListener() {
        mTlInterest.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                mVpContent.setCurrentItem(position, true);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        mRlRequestFailed.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                mPresenter.getInterestInfo("", "1", "", UserInfoBean.getUid(mContext), 1);
            }
        });

        // 发布视频
        mBtnPublishVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String uid = UserInfoBean.getUid(mContext);
                if (TextUtils.isEmpty(uid)) {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(mContext, InterestPublishActivity.class);
                    startActivityForResult(intent, REQUEST_CODE_PUBLISH_VIDEO);
                }
            }
        });
    }

//    /**
//     * 隐藏Toolbar
//     */
//    public void hideToolbar() {
//        int toolHeight = mToolbarContainer.getHeight();
//        mToolbarContainer.animate().translationY(-toolHeight).setInterpolator(new DecelerateInterpolator(2)).startActivityForResult();
//    }
//
//    /**
//     * 显示Toolbar
//     */
//    public void showToolbar() {
//        mToolbarContainer.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).startActivityForResult();
//    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_PUBLISH_VIDEO:
                /*
                  如果当前页面上的tab分类中包含了用户所上传视频的分类
                  则跳转到当前分类并刷新数据
                 */
                if (data == null) {
                    return;
                }
                boolean isPublishSuccess = data.getBooleanExtra("isPublishSuccess", false);
                if (!isPublishSuccess) {
                    return;
                }
                Intent intent = new Intent(mContext, InterestVideoPublishSuccessActivity.class);
                startActivity(intent);
//                String tagName = data.getStringExtra("tagName");
//                for (int i = 0, mTabNamesLength = mTabNames.length; i < mTabNamesLength; i++) {
//                    String tabName = mTabNames[i];
//                    if (tabName.equals(tagName)) {
//                        mVpContent.setCurrentItem(i, true);
//                        InterestContentFragment fragment = (InterestContentFragment) mFragments.get(mVpContent.getCurrentItem());
//                        fragment.updateData();
//                        break;
//                    }
//                }
                break;
        }
    }

    @Override
    public void showProgress() {
        CustomProgressDialog.showLoading(mContext, "请稍候，正在努力加载...", true);
    }

    @Override
    public void hideProgress() {
        CustomProgressDialog.stopLoading();
    }

    @Override
    public void onRequestSuccess(InterestBean interestBean) {
        InterestBean.DataBean bean = interestBean.getData();
        if (isFirstLoad) {
            switch (interestBean.getCode()) {
                case 200:
                    isFirstLoad = false;
                    List<InterestBean.DataBean.TypeBean> type = bean.getType();
                    String[] tabNames = new String[type.size()];
                    for (int i = 0, typeSize = type.size(); i < typeSize; i++) {
                        InterestBean.DataBean.TypeBean typeBean = type.get(i);
                        String typeName = typeBean.getName();
                        mFragments.add(InterestContentFragment.getInstance(typeName));
                        tabNames[i] = typeName;
                    }
                    MyPagerAdapter adapter = new MyPagerAdapter(getChildFragmentManager(),
                            mFragments, tabNames);
                    mVpContent.setAdapter(adapter);
                    mTlInterest.setViewPager(mVpContent);
                    break;
                case 400:
                    showShortText("暂无数据");
                    break;
                case 403:
                    showShortText("获取参数失败");
                    break;
                case 404:
                    showShortText("获取数据失败");
                    break;
            }
        }
        mRlRequestFailed.setVisibility(View.GONE);
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        if (retryCount < 5) {
            mPresenter.getInterestInfo("", "1", "", UserInfoBean.getUid(mContext), 1);
            retryCount++;
        } else {
            mRlRequestFailed.setVisibility(View.VISIBLE);
            retryCount = 0;
        }
    }

    @Override
    public void onReportSuccess(CodeBean bean) {

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            QMUIStatusBarHelper.setStatusBarLightMode(getActivity());
        }
    }
}
